package com.zsh.rabbitmq.springbootrabbitmq.controller;

import com.zsh.rabbitmq.springbootrabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author zsh
 * @Description 发送延迟消息
 * @create 2022-05-06 16:03
 */

@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable("message") String message ){
        log.info("当前时间:{},发送一条信息给两个ttl队列：{}",new Date().toString(),message);

        rabbitTemplate.convertAndSend("X","XA","消息来自TTL为10s：" + message);
        rabbitTemplate.convertAndSend("X","XB","消息来自TTL为40s：" + message);

    }

    //开始发消息，设置消息TTL
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendExpirationMsg(@PathVariable("message") String message,
                                  @PathVariable("ttlTime") String ttlTime){

        log.info("当前时间:{},发送一条时长{}ms的ttl信息给队列QC：{}",
                new Date().toString(),ttlTime,message);
        rabbitTemplate.convertAndSend("X","XC",message,msg ->{
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
    }

    //基于插件发送消息,延迟时间
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendDelayMsg(@PathVariable("message") String message,
                             @PathVariable("delayTime") Integer delayTime){
        log.info("当前时间:{},发送一条时长{}ms的延迟信息给延迟队列delayed.queue：{}",
                new Date().toString(),delayTime,message);

        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE,
                DelayedQueueConfig.DELAYED_ROUTING_KEY,message, msg ->{
            msg.getMessageProperties().setDelay(delayTime); //ms
            return msg;
        });
    }



}
